package google.sites.model.commands;

import com.google.gdata.data.Link;
import com.google.gdata.data.MediaContent;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.data.sites.FileCabinetPageEntry;
import com.google.gdata.data.sites.SitesLink;
import com.google.gdata.data.sites.WebAttachmentEntry;
import com.google.gdata.util.ServiceException;
import dev.tools.design.patterns.command.CommandException;

import java.io.IOException;
import java.net.URL;

/**
 * Created with IntelliJ IDEA.
 * User: Nuno
 * Date: 04-10-2013
 * Time: 15:55
 */
public class UploadWebAttachment extends SitesCommand {
    private String contentUrl;
    private FileCabinetPageEntry fileCabinet;
    private String title;
    private String description;

    @Override
    protected void protectedExecute() throws CommandException {
        MediaContent content = new MediaContent();
        content.setUri(contentUrl);

        WebAttachmentEntry webAttachment = new WebAttachmentEntry();
        webAttachment.setTitle(new PlainTextConstruct(title));
        webAttachment.setSummary(new PlainTextConstruct(description));
        webAttachment.setContent(content);
        webAttachment.addLink(SitesLink.Rel.PARENT, Link.Type.ATOM,
                fileCabinet.getSelfLink().getHref());

        try {
            setResult(getService().insert(new URL(getContentFeedUrl()), webAttachment));
        } catch (IOException | ServiceException e) {
            throw new CommandException(e);
        }
    }

    public UploadWebAttachment setContentUrl(String contentUrl) {
        this.contentUrl = contentUrl;
        return this;
    }

    public UploadWebAttachment setFileCabinet(FileCabinetPageEntry fileCabinet) {
        this.fileCabinet = fileCabinet;
        return this;
    }

    public UploadWebAttachment setTitle(String title) {
        this.title = title;
        return this;
    }

    public UploadWebAttachment setDescription(String description) {
        this.description = description;
        return this;
    }
}
